package springboard.webapp.controller;

import common.exception.InternalServerException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@RestController
@RequestMapping({"/api/contents"})
public class ContentController {

    @Value("${springboard.file-directory:content}")
    String contentDirectory;

    @ApiOperation("获取内容json")
    @GetMapping(value = "/{path}", produces="application/json;charset=UTF-8")
    @RequiresPermissions("contents:rw")
    public void load(@ApiParam("内容路径") @PathVariable("path") String path,
                     @ApiIgnore HttpServletResponse response) {
        path =  "/" + path + ".json";
        File file = new File(contentDirectory, path);
        if(!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
        try(InputStream in = new FileInputStream(file)) {
            StreamUtils.copy(in, response.getOutputStream());
        } catch(IOException x) {
            throw new InternalServerException(x);
        }
    }

    @ApiOperation("更新内容json")
    @PostMapping(value = "/{path}", produces="application/json;charset=UTF-8")
    @RequiresPermissions("contents:rw")
    public void save(@ApiParam("内容路径") @PathVariable("path") String path,
                     @ApiIgnore HttpServletRequest request,
                     @ApiIgnore HttpServletResponse response) {
        path = "/" + path + ".json";
        File file = new File(contentDirectory, path);
        try(OutputStream out = new FileOutputStream(file)) {
            StreamUtils.copy(request.getInputStream(), out);
        } catch(IOException x) {
            throw new InternalServerException(x);
        }
        try(InputStream in = new FileInputStream(file)) {
            StreamUtils.copy(in, response.getOutputStream());
        } catch(IOException x) {
            throw new InternalServerException(x);
        }
    }

}
